package com.fnn.controller;

import com.fnn.entity.User;
import com.fnn.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Controller
public class baseController {
    @Autowired
    private UserService userService;




    /**
     * 到登录页面（如果没被拦截）
     * @param req
     * @param resp
     * @return
     */
    @RequestMapping("/register")     //跳转到注册页面
    public String register(HttpServletRequest req, HttpServletResponse resp){
        String s = login_yanzheng(req, resp);
        if (s!=null){
            return s;
        }else {
            return "/user/LoginRegisterPage";
        }
    }






    /**
     * 登录成功后到首页
     * @param req
     * @param resp
     * @return
     */
    @RequestMapping("/content_page")
    public String content_page(HttpServletRequest req, HttpServletResponse resp){
        String s = login_yanzheng(req, resp);
        if (s!=null){
            return s;
        }else {
            return "/user/LoginRegisterPage";
        }
    }






    /**
     * 拦截有正确session_id的请求
     * @param req
     * @param resp
     * @return
     */
    public String login_yanzheng(HttpServletRequest req,HttpServletResponse resp){
        //获取请求字段中的cookie
        Cookie[] cookies = req.getCookies();
        String session_id="";
        //遍历cookie
        for (int i = 0; cookies != null && i < cookies.length; i++) {
            if (cookies[i].getName().equals("session_id")) {
                session_id = cookies[i].getValue();
                break;
            }
        }
        if (session_id.equals("") || session_id==null){
            return null;
        }else {
            User user = userService.selectBySession(session_id);
            HttpSession session=req.getSession();
            session.setAttribute("user_name",user.getUser_name());
            return "/body/body";
        }
    }
}

